/**
 * Tools.java
 *
 * @author tianli
 * 
 * @date 2011-3-8
 * 
 * Copyright 2011 netease. All rights reserved. 
 */
package com.japher.hackson.utils;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.Random;
import java.util.TimeZone;
import java.util.Vector;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.Bitmap;
import android.graphics.NinePatch;
import android.graphics.Paint;
import android.graphics.Paint.FontMetrics;
import android.util.Log;
import android.view.View;
import android.view.View.MeasureSpec;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.widget.TextView;

import com.baidu.location.BDLocation;

/**
 * @author tianli
 * 
 */
public class Tools
{
	public static final String RMB = "¥";
	public final static String TAG = Tools.class.getName();

	private static final char HEX_DIGITS[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };

	public static String toHexStringNew(byte[] b)
	{ // String to byte
		StringBuilder sb = new StringBuilder(b.length * 2);
		for (int i = 0; i < b.length; i++)
		{
			sb.append(HEX_DIGITS[(b[i] & 0xf0) >>> 4]);
			sb.append(HEX_DIGITS[b[i] & 0x0f]);
		}
		return sb.toString();
	}

	public static String toHexString2(byte[] b)
	{
		/*
		 * String str = new String(b); System.out.println(str); try { //b =
		 * str.getBytes("UTF-8"); } catch (UnsupportedEncodingException e) { //
		 * TODO Auto-generated catch block e.printStackTrace(); }
		 */
		StringBuilder sb = new StringBuilder(b.length * 2);
		for (int i = 0; i < b.length; i++)
		{
			sb.append(HEX_DIGITS[(b[i] & 0xf0) >>> 4]);
			sb.append(HEX_DIGITS[b[i] & 0x0f]);
		}
		return sb.toString();
	}

	public static String md5New(String s)
	{
		try
		{
			// Create MD5 Hash
			MessageDigest digest = java.security.MessageDigest.getInstance("MD5");
			digest.update(s.getBytes("UTF-8"));
			byte messageDigest[] = digest.digest();

			return toHexString2(messageDigest);
		}
		catch (NoSuchAlgorithmException e)
		{
			e.printStackTrace();
		}
		catch (UnsupportedEncodingException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return "";
	}

	public static String getMD5(String message)
	{
		String digest = message;
		try
		{
			MessageDigest algorithm = MessageDigest.getInstance("MD5");
			algorithm.reset();
			algorithm.update(message.getBytes("UTF-8"));
			digest = toHexString2(algorithm.digest());
			digest = digest.toLowerCase();
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
		return digest;
	}

	/**
	 * split number with ',', for example 1000000.00 = 1,000,000.00
	 */
	public static String splitNumber(String number)
	{
		if (!Tools.isEmpty(number))
		{
			String[] array = number.split("\\.");
			number = "";
			if (array.length > 0)
			{
				int digits = array[0].length();
				for (int d = 0; d < digits; d++)
				{
					if (d != 0 && d % 3 == 0)
					{
						number = "," + number;
					}
					number = array[0].charAt(digits - 1 - d) + number;
				}
			}
			if (array.length > 1)
			{
				number += "." + array[1];
			}
		}
		return number;
	}

	private static String toHexString(byte[] bytes)
	{
		StringBuilder hexString = new StringBuilder();
		for (byte b : bytes)
		{
			String str = Integer.toHexString(0xFF & b);
			while (str.length() < 2)
			{
				str = "0" + str;
			}
			hexString.append(str);
		}
		return hexString.toString();
	}

	/**
	 * get C(m,n)
	 * 
	 */
	public static long getCombination(int m, int n)
	{
		if (n < m)
		{
			return 0;
		}
		long result = 1;
		int max, min;
		if (m > n - m)
		{
			max = m;
			min = n - m;
		}
		else
		{
			max = n - m;
			min = m;
		}
		for (int i = n; i > max; i--)
		{
			result *= i;
		}
		result = result / getFactorial(min);
		return result;
	}

	/**
	 * convert dip to pixels
	 * 
	 */
	public static int getPixelByDip(Context context, int dip)
	{
		return (int) (context.getResources().getDisplayMetrics().density * dip + 0.5f);
	}

	public static int getPixelBySp(Context context, int sp)
	{
		return (int) (sp / context.getResources().getDisplayMetrics().scaledDensity);
	}

	public static long getFactorial(int m)
	{
		long result = 1;
		for (int i = 1; i <= m; i++)
		{
			result *= i;
		}
		return result;
	}

	public static long convertTimeMillis(String date)
	{

		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		Date day = null;
		long milis = -1;
		try
		{
			day = format.parse(date);
		}
		catch (ParseException e)
		{
			e.printStackTrace();
		}
		if (day != null)
		{
			milis = day.getTime();
		}
		return milis;

	}

	public static byte[] inputStreamToBytes(InputStream stream)
	{
		if (stream == null)
		{
			return null;
		}
		ByteArrayOutputStream bytesStream = new ByteArrayOutputStream();
		final int blockSize = 512;
		byte[] buffer = new byte[blockSize];
		int count = 0;
		try
		{
			while ((count = stream.read(buffer, 0, blockSize)) > 0)
			{
				bytesStream.write(buffer, 0, count);
			}
		}
		catch (IOException e)
		{
			// AppLog.error(TAG, e.getMessage(), e);
			return null;
		}
		return bytesStream.toByteArray();
	}

	public static boolean isEmpty(CharSequence string)
	{
		if (string == null || string.length() == 0)
		{
			return true;
		}
		return false;
	}

	public static boolean isEmpty(String string)
	{
		if (string == null || "".equals(string))
		{
			return true;
		}
		return false;
	}
	
	public static String stringFilter(String str) { 
        str = str.replaceAll("）", ")").replaceAll("【", "[").replaceAll("（", "(").replaceAll("】", "]") 
                .replaceAll("！", "!").replaceAll("：", ":");// 替换中文标号 
        String regEx = "[『』]"; // 清除掉特殊字符 
        Pattern p = Pattern.compile(regEx); 
        Matcher m = p.matcher(str); 
        return m.replaceAll("").trim(); 
    }

	public static String getStackTrace(Throwable t)
	{
		if (t == null || t.getStackTrace() == null)
		{
			return null;
		}
		StackTraceElement[] stack = t.getStackTrace();
		String trace = "";
		for (StackTraceElement element : stack)
		{
			trace += element.toString();
			trace += "\n";
		}
		return trace;
	}

	public static Date GetDate(String sValue)
	{
		int year = Integer.parseInt(sValue.substring(0, 4));
		int month = Integer.parseInt(sValue.substring(5, 7));
		int day = Integer.parseInt(sValue.substring(8, 10));
		int hour = Integer.parseInt(sValue.substring(11, 13));
		int minute = Integer.parseInt(sValue.substring(14, 16));
		int second = Integer.parseInt(sValue.substring(17, 19));
		Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT+8"));
		calendar.set(Calendar.YEAR, year);
		calendar.set(Calendar.MONTH, month - 1);
		calendar.set(Calendar.DAY_OF_MONTH, day);
		calendar.set(Calendar.HOUR_OF_DAY, hour);
		calendar.set(Calendar.MINUTE, minute);
		calendar.set(Calendar.SECOND, second);
		Date date = calendar.getTime();
		return date;
	}

	public static String[] Split(String src, int split)
	{
		Vector<String> temp = new Vector<String>();
		int index = -1;
		String tsrc = src;
		while (true)
		{
			index = tsrc.indexOf(split);
			if (index > 0)
			{
				String t = tsrc.substring(0, index);
				temp.addElement(t);
				tsrc = tsrc.substring(index + 1);
			}
			else if (index == 0)
			{
				temp.addElement("");
				tsrc = tsrc.substring(index + 1);
			}
			else
			{
				temp.addElement(tsrc);
				break;
			}
		}
		String[] r = new String[temp.size()];
		temp.copyInto(r);
		return r;
	}

	public static ArrayList<Integer> randomPick(ArrayList<Integer> array, int count)
	{
		if (array == null)
		{
			return new ArrayList<Integer>();
		}
		if (count > array.size())
		{
			return array;
		}
		Integer[] indices = new Integer[array.size()];
		for (int i = 0; i < indices.length; i++)
		{
			indices[i] = i;
		}
		int size = indices.length;
		Random random = new Random();
		// shuffle algorithm
		for (int i = 0; i < size; i++)
		{
			int rand = random.nextInt(size - i);
			// swap array[i] and array[rand + i]
			int temp = indices[i + rand];
			indices[i + rand] = indices[i];
			indices[i] = temp;
		}
		ArrayList<Integer> list = new ArrayList<Integer>();
		for (int i = 0; i < count; i++)
		{
			list.add(array.get(indices[i]));
		}
		Collections.sort(list, new Comparator<Integer>()
		{
			public int compare(Integer object1, Integer object2)
			{
				if (object1 < object2)
				{
					return -1;
				}
				else if (object1.equals(object2))
				{
					return 0;
				}
				return 1;
			}
		});
		return list;
	}

	// public static String getReleaseLabel(String date)
	// {
	//
	// }

	static SimpleDateFormat simpledate = new SimpleDateFormat("yyyy年MM月dd日");

	public static String getDate(String value)
	{
		long date = 0;
		try
		{
			date = Long.valueOf(value);
		}
		catch (Exception e)
		{
		}

		if (date != 0)
		{
			Calendar ca = Calendar.getInstance();
			ca.setTime(new Date(date));
			return simpledate.format(ca.getTime());
		}
		else
		{
			return "";
		}
	}

	public static String getCurrentDateStr()
	{
		SimpleDateFormat simpledate = new SimpleDateFormat("yyyy年MM月dd日");
		Calendar ca = Calendar.getInstance();
		ca.setTime(new Date());
		return simpledate.format(ca.getTime());
	}

	static void putInt(byte array[], int offset, int val)
	{
		array[offset] = (byte) (val & 0xFF);
		val = val >> 8;
		array[offset + 1] = (byte) (val & 0xFF);
		val = val >> 8;
		array[offset + 2] = (byte) (val & 0xFF);
		val = val >> 8;
		array[offset + 3] = (byte) (val & 0xFF);
	}

	/**
	 * 获取9patch chunk参数
	 * 
	 * @param xDivs
	 *            X轴上的分割点（不含边界）
	 * @param yDivs
	 *            Y轴上的分割点（不含边界）
	 * @return
	 */
	public static byte[] getChunk(int xDivs[], int yDivs[])
	{
		byte numXDivs = (byte) xDivs.length;
		byte numYDivs = (byte) yDivs.length;
		byte numColors = 0;
		int paddingLeft = 10;
		int offset = 0;
		numColors = (byte) ((numXDivs + 1) * (numYDivs + 1));
		int size = 32 + (numXDivs + numYDivs + numColors) * 4;
		byte chunk[] = new byte[size];
		chunk[0] = 0;
		chunk[1] = numXDivs;
		chunk[2] = numYDivs;
		chunk[3] = numColors;

		// 以下值无意义
		byte pVal = 0;
		chunk[4] = pVal;
		chunk[5] = pVal;
		chunk[6] = pVal;
		chunk[7] = pVal;

		chunk[8] = pVal;
		chunk[9] = pVal;
		chunk[10] = pVal;
		chunk[11] = pVal;
		// 12-16 pading
		offset = 12;
		for (int i = 0; i < 4; i++)
		{
			putInt(chunk, offset, paddingLeft);
			offset += 4;
		}

		// 10,11,38,50
		offset = 32;
		for (int i = 0; i < xDivs.length; i++)
		{
			putInt(chunk, offset, xDivs[i]);
			offset += 4;
		}
		/*
		 * putInt(chunk,offset,xDivs[1]); offset+=4;
		 */
		for (int i = 0; i < yDivs.length; i++)
		{
			putInt(chunk, offset, yDivs[i]);
			offset += 4;
		}
		// putInt(chunk,offset,yDivs[1]);
		// offset+=4;

		int color = 0x00000F;
		int color2 = 0xFFFFF0;

		int colorInc = (color2 - color) / numColors;

		/*
		 * for(int i=0;i<numColors;i++) { putInt(chunk,offset,0x2F000000|color);
		 * offset+=4; color+=colorInc; }
		 */

		for (int i = 0; i < numColors; i++)
		{
			putInt(chunk, offset, 1);
			offset += 4;
			// color+=colorInc;
		}
		return chunk;
	}

	/**
	 * 构造9patch对象
	 * 
	 * @param bm
	 * @param xDivs
	 *            X轴上的分割点（不含边界）
	 * @param yDivs
	 *            Y轴上的分割点（不含边界）
	 * @return
	 */
	public static NinePatch getNinePatch(Bitmap bm, int xDivs[], int yDivs[])
	{

		NinePatch img9Patch = new NinePatch(bm, getChunk(xDivs, yDivs), null);

		return img9Patch;
	}

	/**
	 * 取汉字的首字母，仅对GB2312一级常用字（3700多）可用，二级GBK字库不可用
	 * 
	 * @param str
	 * @return
	 */
	public static String getPY(String src)
	{
		String result = "";
		if (src == null || src.trim().length() == 0)
			return "";
		byte word[] = null;
		try
		{

			word = src.trim().getBytes("gbk");
		}
		catch (UnsupportedEncodingException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
			return result;
		}
		catch (RuntimeException e)
		{
			e.printStackTrace();
			return result;
		}
		int sp = 0;
		do
		{
			if (word[sp] > 0)
			{
				result += new String(word, sp, 1);
				sp++;
			}
			else
			{
				int b0 = word[sp] + 256;
				int b1 = word[sp + 1] + 256;

				result += getWord(b0 * 256 + b1);
				sp += 2;
			}
		} while (sp < word.length);
		return result;
	}

	private static String getWord(int iCnChar)
	{
		if ((iCnChar >= 45217) && (iCnChar <= 45252))
		{
			return "A";
		}
		else if ((iCnChar >= 45253) && (iCnChar <= 45760))
		{
			return "B";
		}
		else if ((iCnChar >= 45761) && (iCnChar <= 46317))
		{
			return "C";
		}
		else if ((iCnChar >= 46318) && (iCnChar <= 46825))
		{
			return "D";
		}
		else if ((iCnChar >= 46826) && (iCnChar <= 47009))
		{
			return "E";
		}
		else if ((iCnChar >= 47010) && (iCnChar <= 47296))
		{
			return "F";
		}
		else if ((iCnChar >= 47297) && (iCnChar <= 47613))
		{
			return "G";
		}
		else if ((iCnChar >= 47614) && (iCnChar <= 48118))
		{
			return "H";
		}
		else if ((iCnChar >= 48119) && (iCnChar <= 49061))
		{
			return "J";
		}
		else if ((iCnChar >= 49062) && (iCnChar <= 49323))
		{
			return "K";
		}
		else if ((iCnChar >= 49324) && (iCnChar <= 49895))
		{
			return "L";
		}
		else if ((iCnChar >= 49896) && (iCnChar <= 50370))
		{
			return "M";
		}

		else if ((iCnChar >= 50371) && (iCnChar <= 50613))
		{
			return "N";
		}
		else if ((iCnChar >= 50614) && (iCnChar <= 50621))
		{
			return "O";
		}
		else if ((iCnChar >= 50622) && (iCnChar <= 50905))
		{
			return "P";
		}
		else if ((iCnChar >= 50906) && (iCnChar <= 51386))
		{
			return "Q";
		}
		else if ((iCnChar >= 51387) && (iCnChar <= 51445))
		{
			return "R";
		}
		else if ((iCnChar >= 51446) && (iCnChar <= 52217))
		{
			return "S";
		}
		else if ((iCnChar >= 52218) && (iCnChar <= 52697))
		{
			return "T";
		}
		else if ((iCnChar >= 52698) && (iCnChar <= 52979))
		{
			return "W";
		}
		else if ((iCnChar >= 52980) && (iCnChar <= 53640))
		{
			return "X";
		}
		else if ((iCnChar >= 53689) && (iCnChar <= 54480))
		{
			return "Y";
		}
		else if ((iCnChar >= 54481) && (iCnChar <= 55289))
		{
			return "Z";
		}
		else
			return ("?");

	}


	/*
	 * 生成密钥 encodeKeyA.length=24
	 */
	public static byte[] genCroptyKey(byte[] encodeKeyA, String randomStrB)
	{
		if (encodeKeyA == null)
		{
			return null;
		}

		// byte[] B = new byte[24];
		byte[] C = null;
		try
		{
			C = randomStrB.getBytes("utf-8");
		}
		catch (UnsupportedEncodingException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}

		int clen = C.length;
		if (encodeKeyA.length != 24 || (clen < 8 || clen > 20))
			return null;

		byte[] result = new byte[24];
		for (int i = 0; i < encodeKeyA.length; i++)
		{ // 0 & 1 | 2 ^

			switch (i % 3)
			{
				case 0:
					result[i] = (byte) (encodeKeyA[i] & (C[i % C.length] + i));
					break;
				case 1:
					result[i] = (byte) (encodeKeyA[i] | (C[i % C.length] + i));
					break;
				case 2:
					result[i] = (byte) (encodeKeyA[i] ^ (C[i % C.length] + i));
					break;
			}

		}

		System.out.println("key=" + result.toString());

		return result;
	}

	public static int measureTextHeight(Paint paint)
	{
		FontMetrics fm = paint.getFontMetrics();
		return (int) (Math.ceil(fm.descent - fm.ascent) + 2);
	}

	public static int getPackageVersionCode(Context context) throws NameNotFoundException
	{
		String name = context.getPackageName();
		PackageInfo pinfo = context.getPackageManager().getPackageInfo(name, PackageManager.GET_CONFIGURATIONS);
		return pinfo.versionCode;
	}

	public static boolean isMobileNO(String mobiles)
	{
		Pattern p = Pattern.compile("^((13[0-9])|(15[^4,\\D])|(18[0,5-9]))\\d{8}$");
		Matcher m = p.matcher(mobiles);
		return m.matches();
	}

	public static boolean isEmailValid(String email)
	{

		// String
		// str="^([a-zA-Z0-9]*[-_]?[a-zA-Z0-9]+)*@([a-zA-Z0-9]*[-_]?[a-zA-Z0-9]+)+[\\.][A-Za-z]{2,3}([\\.][A-Za-z]{2})?$";
		// Pattern p = Pattern.compile(str);
		// Matcher m = p.matcher(email);
		// return m.matches();
		boolean result = false;
		if (!Tools.isEmpty(email) && email.contains("@") && email.contains("."))
		{
			int index = email.indexOf("@");
			if (index != -1 && index != 0 && index != email.length())
			{
				index = email.indexOf(".");
				if (index != -1 && index != 0 && index != email.length())
				{
					result = true;
				}
			}
		}
		return result;
	}

	// TextView截取最大的maxLine行的内容
	public static void truncateTextViewByMaxLine(final TextView view, final int maxLine)
	{
		ViewTreeObserver vto = view.getViewTreeObserver();
		vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener()
		{

			public void onGlobalLayout()
			{
				if (view.getLineCount() > maxLine)
				{
					int lineEndIndex = view.getLayout().getLineEnd(maxLine - 1);
					String text = view.getText().subSequence(0, lineEndIndex - 3) + "...";
					view.setText(text);
				}
			}
		});
	}

	public static String parseSellPhoneNumber(String phoneNum)
	{
		String result = phoneNum;
		if (!isEmpty(phoneNum) && phoneNum.length() == 11)
		{
			String first = phoneNum.substring(0, 3);
			String seconde = phoneNum.substring(7, 11);
			result = first + "****" + seconde;
		}
		return result;
	}

	public static boolean isBaiduGeoSuccess(BDLocation arg0)
	{
		boolean result = false;
		if (arg0 != null && arg0.getLocType() != 63 && !(arg0.getLocType() >= 162 && arg0.getLocType() <= 167))
		{
			result = true;
		}
		return result;
	}

	public static String floatToStr(float value, boolean needZero)
	{
		String str = value + "";
		int index = str.indexOf(".");
		if (index != -1 && str.length() > index + 1)
		{
			try
			{
				str = str.substring(0, index + 2);
				if (!needZero && ".0".equals(str.subSequence(index, index + 1)))
				{
					str = str.substring(index);
				}
			}
			catch (Exception e)
			{
			}
		}
		return str;
	}

	public static float strToFloat(String value)
	{
		float result = 0.00f;
		try
		{
			result = Float.parseFloat(value);
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
		return result;
	}
	
	public static long strToLong(String value)
	{
		long result = 0L;
		try
		{
			result = Long.parseLong(value);
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
		return result;
	}

	public static int strToInt(String value)
	{
		int result = 0;
		try
		{
			result = Integer.parseInt(value);
		}
		catch (Exception e)
		{
			// e.printStackTrace();
		}
		return result;
	}

//	public static void changeFont(ViewGroup parent, Typeface mTypeFace)
//	{
//		if(mTypeFace == null) return;
//		for (int i = 0; i < parent.getChildCount(); i++)
//		{
//			View view = parent.getChildAt(i);
//			if (view instanceof TextView && mTypeFace != null)
//			{
//				TextView text = (TextView) view;
//				
//				TypefaceUtils.setFont(text, mTypeFace);
//			}
//			else if (view instanceof ViewGroup)
//			{
//				changeFont((ViewGroup) view, mTypeFace);
//			}
//		}
//	}

	private static double EARTH_RADIUS = 6378.137; 

    private static double rad(double d) 
    { 
        return d * Math.PI / 180.0; 
    } 
    
    //公里 km
	public static double getDistance(double lat1, double lng1, double lat2,double lng2)
	{
		double radLat1 = rad(lat1);

		double radLat2 = rad(lat2);

		double a = radLat1 - radLat2;

		double b = rad(lng1) - rad(lng2);

		double s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2)

		+ Math.cos(radLat1) * Math.cos(radLat2)

		* Math.pow(Math.sin(b / 2), 2)));

		s = s * EARTH_RADIUS;

		s = Math.round(s * 10000) / 10000;

		return s;
	}

	
	public static void measureView(View child) {
		ViewGroup.LayoutParams p = child.getLayoutParams();
		if (p == null) {
			p = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
					ViewGroup.LayoutParams.WRAP_CONTENT);
		}

		int childWidthSpec = ViewGroup.getChildMeasureSpec(0, 0 + 0, p.width);
		int lpHeight = p.height;
		int childHeightSpec;
		if (lpHeight > 0) {
			childHeightSpec = MeasureSpec.makeMeasureSpec(lpHeight,
					MeasureSpec.EXACTLY);
		} else {
			childHeightSpec = MeasureSpec.makeMeasureSpec(0,
					MeasureSpec.UNSPECIFIED);
		}
		child.measure(childWidthSpec, childHeightSpec);
	}
	
	public static void ellipsizeTextEnd(TextView floder,boolean isFolder,String text,int maxLine)
	{
		if(text == null)
		{
			text = "";
		}
		
		floder.setText(text);
		
		if(isFolder)
		{
			floder.invalidate();
			floder.requestLayout();
			Log.v("ellipsizeTextEnd", "floder.getLineCount is "+floder.getLineCount());
			if (floder.getLineCount() > maxLine)
			{
                int lineEndIndex = floder.getLayout().getLineEnd(maxLine - 1);
                String textOfDesc = text.subSequence(0,
                        lineEndIndex - 3)
                        + "...";
                floder.setText(textOfDesc);
            }
		}
		floder.invalidate();
		floder.requestLayout();
	}
	
	
	
	
	public static String ellipsizeTextEnd(String content, Paint p, float width,int ellipsizeTextEndLine)
	{
		String []lines=autoSplit(content, p, width);
		StringBuffer sbBuf=new StringBuffer();
		if(lines!=null&&lines.length>0)
		{
			int index=0;
			while(index<lines.length)
			{
				if(index<ellipsizeTextEndLine-1)
				{
					sbBuf.append(lines[index]);
				}
				else 
				{
					String textEnd="...";
					if(lines[index].length()>3)
					{
						textEnd = lines[index].subSequence(0,
								lines[index].length() - 3)
		                        + "...";
					}
					
					sbBuf.append(textEnd);
					break;
					
				}
				index++;
				
			}
		}
		return sbBuf.toString();
	}
	
	public static String[] autoSplit(String content, Paint p, float width) { 
		if(!Tools.isEmpty(content)&&p!=null&&width>0)
		{
			int length = content.length(); 
	        float textWidth = p.measureText(content); 
	        if(textWidth <= width) { 
	            return new String[]{content}; 
	        } 
	         
	        int start = 0, end = 1, i = 0; 
	        int lines = (int) Math.ceil(textWidth / width); //计算行数 
	        String[] lineTexts = new String[lines]; 
	        while(start < length) { 
	            if(p.measureText(content, start, end) > width) { //文本宽度超出控件宽度时 
	                lineTexts[i++] = (String) content.subSequence(start, end); 
	                start = end; 
	            } 
	            if(end == length) { //不足一行的文本 
	                lineTexts[i] = (String) content.subSequence(start, end); 
	                break; 
	            } 
	            end += 1; 
	        } 
	        return lineTexts; 
		}
		return null;
        
    } 

	
	public static String parseCityCnName(String name)
	{
		String result = null;
		
		if(!Tools.isEmpty(name))
		{
			if(name.endsWith("市"))
			{
				name = name.substring(0, name.length()-1);
			}
			
			if(name.length() > 3 )
			{
				name = name.substring(0,3);
				name = name + "..";
			}
			
			result = name;
		}
		return result;
	}

	
	 /**
	  * 清零
	  * @param str 原始字符串
	  * @return
	  */
	public static String shortenRMB(String price)
	{
		if (price.indexOf(".") != -1 && price.charAt(price.length() - 1) == '0') 
		{
			return shortenRMB(price.substring(0, price.length() - 1));
		}
		else 
		{
			return price.charAt(price.length() - 1) == '.' ? price.substring(0, price.length() - 1) : price;
		}
	}
}
